package com.xms.sdk.core;

import com.xms.schema.core.AttributeTypeIds;
import com.xms.schema.entity.Attribute;
import com.xms.utils.UUIDUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 值类型转换器
 * </p>
 *
 * @author migo
 * @since 2021/10/12
 */
public class ValueConverter {

    public static boolean toBoolean(String value) {
        boolean returnValue = false;
        if ("1".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) ||
                "true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value))
            returnValue = true;
        return returnValue;
    }

    public static LocalDateTime toLocalDateTime(String value){
        /*if(!RegexUtil.isDateTime(value))
            return null;*/
        String dtValue = value.replace("/", "-");
        if(value.length() <= 10)
            dtValue += " 00:00:00";
        return LocalDateTime.parse(dtValue, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static Object toAttributeType(Attribute attribute, Object value){
        switch (attribute.getAttributetypename()){
            case AttributeTypeIds.NVARCHAR:
            case AttributeTypeIds.NTEXT:
            case AttributeTypeIds.TEXT:
                return String.valueOf(value);

            case AttributeTypeIds.INT:
            case AttributeTypeIds.SMALLINT:
            case AttributeTypeIds.PICKLIST:
            case AttributeTypeIds.STATUS:
                return Integer.valueOf(value.toString());

            case AttributeTypeIds.FLOAT:
            case AttributeTypeIds.MONEY:
                return Float.valueOf(value.toString());

            case AttributeTypeIds.STATE:
            case AttributeTypeIds.BIT:
                return toBoolean(value.toString());

            case AttributeTypeIds.DATETIME:
            case AttributeTypeIds.SMALLDATETIME:
                return toLocalDateTime(value.toString());

            case AttributeTypeIds.LOOKUP:
            case AttributeTypeIds.CUSTOMER:
            case AttributeTypeIds.OWNER:
                return UUIDUtil.get(value.toString());

            default:
                return value;
        }
    }
}
